<?php

declare(strict_types=1);

namespace App\Model\Act;

use Hyperf\DbConnection\Model\Model;

/**
 * 许愿树礼物配置
 */
class WishTreeGift extends Model
{
    protected $table = 'act_wish_tree_gift';

    static function getConf($byKey = false)
    {
        $data = self::where(['flag' => 1])->get()->toArray();
        $list = [];
        foreach ($data as $item) $list[$item['gift_id']] = $item;
        return $byKey ? $list : $data;
    }

    /**
     * 获取礼物
     */
    static function getGiftIds($num = 1)
    {
        $conf = WishTreeGift::getConf(true);
        $remainGiftIds = WishTree::getRemainGifts($conf);
        $gifts = $rid = [];
        foreach ($conf as $val) {
            $giftId = $val['gift_id'];
            if ($remainGiftIds[$giftId] <= 0) continue;
            $gifts[$giftId] = intval($val['gift_percent'] * 1000);
        }
        for ($i = 0; $i < $num; $i++) {
            $giftId = self::getRand($gifts);
            $remainGiftIds[$giftId]--;
            array_push($rid, $giftId);
            if ($remainGiftIds[$giftId] <= 0) unset($gifts[$giftId]);
        }
        return array_count_values($rid);
    }

    /**
     * 计算概率
     */
    static function getRand($proArr)
    {
        $result = '';
        //概率数组的总概率精度   
        $proSum = array_sum($proArr);
        //概率数组循环   
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset($proArr);
        return $result;
    }
}
